package com.sskj.gcc.market;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bulong.rudeness.RudenessScreenHelper;
import com.sskj.common.rxbus2.BusData;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.depthlib.data.DepthData;
import com.sskj.depthlib.view.DepthMapView;
import com.sskj.gcc.R;
import com.sskj.gcc.market.data.BuySellData;
import com.sskj.gcc.market.data.DeepData;
import com.sskj.gcc.market.utils.NumberUtils;
import com.sskj.gocoin.common.MarketWebSocket;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.m.HttpConfig;
import com.sskj.gocoin.utils.GsonUtil;
import com.sskj.gocoin.v.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.util.CoinUtil;
import com.sskj.market.R2;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author Hey
 * Create at  2019/07/31 10:25:20
 */
public class DepthFragment extends BaseFragment<MarketDetailActivity, DeepthPresenter> {


    @BindView(R2.id.depthMapView)
    DepthMapView depthMapView;
    @BindView(R2.id.deepRecyclerView)
    RecyclerView deepRecyclerView;
    @BindView(R2.id.depthMapTip)
    LinearLayout depthMapTip;
    @BindView(R2.id.buy_count_title)
    TextView buyCountTitle;
    @BindView(R2.id.sell_count_title)
    TextView sellCountTitle;
    @BindView(R2.id.price_title)
    TextView priceTitle;

    private BaseAdapter<DeepData> deepListAdapter;

    private String code;
    private Disposable disposable;

    private MarketWebSocket webSocket;

    private MarketWebSocket pankouWebSocket;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RxBus.getDefault().register(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.market_fragment_deepth;
    }

    @Override
    public DeepthPresenter getPresenter() {
        return new DeepthPresenter();
    }

    @Override
    public void initView() {
        if (getArguments() != null) {
            code = getArguments().getString("code");
            setCountTitle(code);
        }

        deepRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        deepListAdapter = new BaseAdapter<DeepData>(com.sskj.market.R.layout.market_item_deep_list, null, deepRecyclerView) {
            @Override
            public void bind(ViewHolder holder, DeepData item) {
                holder.setText(com.sskj.market.R.id.buy_position, holder.getLayoutPosition() + 1 + "")
                        .setText(R.id.sell_position, holder.getLayoutPosition() + 1 + "")
                        .setText(R.id.buy_count, NumberUtils.keepMaxDown(item.getBuyCount(), 4))
                        .setText(R.id.buy_price, CoinUtil.keepCoinPrice(code, String.valueOf(item.getBuyPrice())))
                        .setText(R.id.sell_count, NumberUtils.keepMaxDown(item.getSellCount(), 4))
                        .setText(R.id.sell_price,CoinUtil.keepCoinPrice(code, String.valueOf(item.getSellPrice())));
            }
        };
    }

    private void setCountTitle(String code) {
        String name = code.replace("/", "_");
        String unit = "USDT";
        if (name.contains("_")) {
            unit = name.split("_")[1].toUpperCase();
            name = name.split("_")[0].toUpperCase();
        }
        priceTitle.setText(getString(R.string.app_price_usdt) + "(" + unit + ")");
        sellCountTitle.setText(getString(com.sskj.market.R.string.marketdepthFragment1) + "(" + name + ")");
        buyCountTitle.setText(getString(com.sskj.market.R.string.marketdepthFragment1) + "(" + name + ")");
    }


    @Override
    public void initData() {
        depthMapView.setShader(true,color(R.color.lib_depth_buy_top), color(R.color.lib_depth_buy_middle), color(R.color.lib_depth_buy_bottom), 1000);
        depthMapView.setShader(false, color(R.color.lib_depth_sell_top), color(R.color.lib_depth_sell_middle), color(R.color.lib_depth_sell_bottom), 1000);
        depthMapView.mPriceLimit = CoinUtil.getPriceKeepNum(code);
        depthMapView.mPopTopMargin = RudenessScreenHelper.dp2px(getActivity(),30);
    }


    @Override
    public void lazyLoad() {
        mPresenter.getDeepData(code);
        mPresenter.getPanKouData(code);
        startWebSocket();
    }

    /**
     * K线点击抽屉切换code
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeCoin(BusData<CoinBean> busData) {
        if ("KLevel".equals(busData.getId())) {
            code = busData.getData().getCode();
            mPresenter.getDeepData(code);
            mPresenter.getPanKouData(code);
            startWebSocket();
            setCountTitle(code);
            depthMapView.mPriceLimit = CoinUtil.getPriceKeepNum(code);
        }
    }

    public static DepthFragment newInstance(String code) {
        DepthFragment fragment = new DepthFragment();
        Bundle bundle = new Bundle();
        bundle.putString("code", code);
        fragment.setArguments(bundle);
        return fragment;
    }


    //设置深度图数据
    public void setDeepMap(BuySellData data) {
        depthMapView.setData(data.getBids(), data.getAsks());
        depthMapTip.setVisibility(View.VISIBLE);
    }

    /**
     * 设置深度列表数据
     */
    public void setDeepData(BuySellData buySellData) {
        disposable = Flowable.just(buySellData)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(buySellData1 -> {
                    if (buySellData1.getAsks() != null && buySellData1.getBids() != null) {
                        List<DeepData> data = new ArrayList<>();
                        //使买盘和买盘数据量保持一致
                        while (buySellData1.getAsks().size() > buySellData1.getBids().size()) {
                            buySellData1.getBids().add(new DepthData());
                        }
                        while (buySellData1.getAsks().size() < buySellData1.getBids().size()) {
                            buySellData1.getAsks().add(new DepthData());
                        }
                        //组合卖盘数据
                        for (DepthData item : buySellData1.getAsks()) {
                            DeepData itemData = new DeepData();
                            itemData.setSellCount(item.getTotalSize());
                            itemData.setSellPrice(item.getPrice());
                            data.add(itemData);
                        }
                        //组合买盘数据
                        for (int i = 0; i < buySellData1.getBids().size(); i++) {
                            DepthData item = buySellData1.getBids().get(i);
                            data.get(i).setBuyCount(item.getTotalSize());
                            data.get(i).setBuyPrice(item.getPrice());
                        }
                        return data;
                    }

                    return null;
                })
                .subscribe(data -> {
                    deepListAdapter.setNewData(data);
                }, Throwable::printStackTrace);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
        if (disposable != null) {
            disposable.dispose();
        }
        if (webSocket != null) {
            webSocket.closeWebSocket();
        }
        if (pankouWebSocket!=null){
            pankouWebSocket.closeWebSocket();
        }
    }


    public void startWebSocket() {
        JSONObject message = new JSONObject();
        try {
            message.put("code", code);
            if (webSocket==null) {
                webSocket = new MarketWebSocket(HttpConfig.WS_DEPTH, "depth", message.toString());
                webSocket.setListener(message1 -> {
                    BuySellData data = GsonUtil.GsonToBean(message1, BuySellData.class);
                    if (data != null) {
                        setDeepMap(data);
                    }
                });
            }else {
                webSocket.sendMessage(message.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        String text = "{\"code\":\"" + code + "\"}";
        if (pankouWebSocket == null) {
            pankouWebSocket = new MarketWebSocket(HttpConfig.BTC_PK, "pankou", text);
            pankouWebSocket.setListener(message2 -> {
                BuySellData data = GsonUtil.GsonToBean(message2, BuySellData.class);
                if (data != null) {
                    setDeepData(data);
                }
            });
        }else {
            pankouWebSocket.sendMessage(text);
        }


    }

    public void setDeepOrder(BuySellData data) {
        setDeepData(data);
    }
}
